package com.penngo.gui.dfdiff.view;

import com.penngo.gui.dfdiff.utils.GB;
import org.apache.pdfbox.multipdf.PDFMergerUtility;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;

import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.io.File;
import java.io.IOException;

public class Img2PdfDialog extends BaseDialog{

    private JTextField mergePath;
    private JTextField pdfFile;
    private JFileChooser folderChooser;
    private JFileChooser fileChooser;
    public Img2PdfDialog() {
//        System.out.println("Img2PdfDialog==========");
//        setSize(400, 200);
    }

    @Override
    public void initUI() {
        setSize(600, 200);
        JLabel pathLabel = new JLabel("需要转换的图片路径：");
        this.add(pathLabel, new GB(0,0,1,1).setInsets(10));
        mergePath = new JTextField();
        this.add(mergePath, new GB(1,0,1,1).setFill(GB.BOTH).setWeight(100, 0).setInsets(10));
        JButton openBtn = new JButton("选择");
        openBtn.addActionListener(e -> openFolder());
        this.add(openBtn, new GB(2,0,1,1).setInsets(10));

        JLabel pdfLabel = new JLabel("转换后的PDF路径：");
        this.add(pdfLabel, new GB(0,1,1,1).setInsets(10));
        pdfFile = new JTextField();
        this.add(pdfFile, new GB(1,1,1,1).setFill(GB.BOTH).setWeight(100, 0).setInsets(10));
        JButton fileBtn = new JButton("选择");
        fileBtn.addActionListener(e -> savePdfName());
        this.add(fileBtn, new GB(2,1,1,1).setInsets(10));

        JButton saveBtn = new JButton("开始转换");
        saveBtn.addActionListener(e -> transform2Pdf());
        this.add(saveBtn, new GB(0,2,2,1).setInsets(10));
    }

    private void openFolder(){
        if(folderChooser == null){
            folderChooser = new JFileChooser(".");
            folderChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
        }

        int result = folderChooser.showOpenDialog(null);
        if(result == JFileChooser.APPROVE_OPTION){
            File selectFile = folderChooser.getSelectedFile();
            if(selectFile.isFile()){
                selectFile = selectFile.getParentFile();
            }
            //node = new ProjectNode(selectFile.getName(), selectFile,null, ProjectNode.ProjectType.FOLDER);
            mergePath.setText(selectFile.getAbsolutePath());
            String saveFile = selectFile.getParentFile().getAbsolutePath()  + File.separatorChar + "image2pdf.pdf";
            pdfFile.setText(saveFile);
        }
    }

    private void transform2Pdf(){
        try{
            File f = new File(pdfFile.getText());
            if(f.exists()){
                int yes_ok = JOptionPane.showConfirmDialog(null, "文件已存在，是否覆盖？", "提示", JOptionPane.YES_NO_OPTION);
                if(yes_ok == JOptionPane.YES_OPTION){
                    merge();
                }
            }
            else{
                merge();
            }
        }
        catch(Exception e){
            e.printStackTrace();
        }
    }

    private void merge() throws Exception{
        PDDocument document = new PDDocument();
        File[] imgs = new File(mergePath.getText()).listFiles();
        for(File img:imgs){
            String name = img.getName().toLowerCase();
            if (name.endsWith(".jpg") || name.endsWith(".jpeg") ||  name.endsWith(".png") ||
                    name.endsWith(".gif")|| name.endsWith(".bmp")|| name.endsWith(".tif") ||
                    name.endsWith(".tiff") || name.endsWith(".webp")){
                // System.out.println("img:"+img.getAbsolutePath());
                // 创建一个新页面
                PDPage page = new PDPage(PDRectangle.A4);
                document.addPage(page);
                // 加载图片
                PDImageXObject pdImage = PDImageXObject.createFromFile(img.getAbsolutePath(), document);

                // 计算图片在A4页面上的缩放比例
                float scale = Math.min(page.getMediaBox().getWidth() / pdImage.getWidth(),
                        page.getMediaBox().getHeight() / pdImage.getHeight());

                // 计算图片在页面上的位置
                float x = (page.getMediaBox().getWidth() - pdImage.getWidth() * scale) / 2;
                float y = (page.getMediaBox().getHeight() - pdImage.getHeight() * scale) / 2;

                // 创建内容流
                PDPageContentStream contentStream = new PDPageContentStream(document, page);
                // 在页面上绘制图片
                contentStream.drawImage(pdImage, x, y, pdImage.getWidth() * scale, pdImage.getHeight() * scale);
                contentStream.close();

            }
        }

        // 保存文档
        document.save(pdfFile.getText());
//        System.out.println("PDF created successfully.");

        JOptionPane.showMessageDialog(null, "转换完成");
    }
    private void savePdfName(){
        if(fileChooser == null){
            fileChooser = new JFileChooser();
            FileNameExtensionFilter filter = new FileNameExtensionFilter(
                    "PDF(*.pdf)", "pdf");
            fileChooser.addChoosableFileFilter(filter);
        }
        fileChooser.setSelectedFile(new File(mergePath.getText()));
        int returnVal = fileChooser.showSaveDialog(null);
        if(returnVal == JFileChooser.APPROVE_OPTION) {
            File f = fileChooser.getSelectedFile();
            String fullname = fileChooser.getCurrentDirectory().getAbsolutePath() + File.separatorChar + f.getName();
            pdfFile.setText(fullname);
        }
    }
    public static void main(String[] args) {
        Img2PdfDialog dialog = new Img2PdfDialog();
        dialog.setVisible(true);
    }

}
